#pragma once

#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <regex>

namespace zeroplus::mq
{
    class Uri
    {
    private:
        std::vector<std::string> parts;
        std::string scheme_;
        std::string host_;
        std::string ip_;
        std::string port_;
        std::string address_;
        std::string uri_;

    public:
        Uri() = default;
        Uri(const std::string &address)
            : address_(address)
        {
            ParseURI();
        }
        Uri(const std::string &scheme, const std::string &ip, const std::string &port)
            : scheme_(scheme),
              ip_(ip),
              port_(port)
        {
            uri_ = scheme_ + "://" + ip_ + ":" + port_;
        }

        ~Uri()
        {
        }

        std::string GetUri() { return uri_; }
        std::string GetNextUri(int offset)
        {
            uint32_t port = std::stoi(port_);
            std::string nextPort = std::to_string(port + offset);
            return scheme_ + "://" + ip_ + ":" + nextPort;
        }
        std::string GetIP() { return ip_; }
        int GetPort() { return std::stoi(port_); }

    private:
        // 解析 URI 并设置成员变量
        void ParseURI()
        {
            std::regex uriRegex(R"(^(\w+)://([^/]+)(/?)(.*)$)");
            std::smatch match;
            if (std::regex_match(address_, match, uriRegex))
            {
                scheme_ = match.str(1);
                host_ = match.str(2);
                std::vector<std::string> result;
                boost::split(result, host_, boost::is_any_of(":"));
                ip_ = result[0];
                port_ = result[1];
                uri_ = match.str(1) + "://" + match.str(2);
                LOG_DEBUG("scheme=%s, host=%s, uri=%s", scheme_.c_str(), host_.c_str(), uri_.c_str());
            }
            else
            {
                throw std::runtime_error("Invalid URI format");
            }
        }
    };
}
